﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using {Namespace};
using SqlSugar;
namespace OpenAuth.App
{
    public class {ModuleCode} : SqlSugarBaseApp<{ClassName}>
    {
        private {SubModuleCode} _{SubClassName}App;
        /// <summary>
        /// 加载列表
        /// </summary>
        public async Task<PagedDynamicDataResp> Load(Query{ClassName}ListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }

            var result = new PagedDynamicDataResp();
            var objs = GetDataPrivilege("u");
            if (!string.IsNullOrEmpty(request.key))
            {
                objs = objs.Where(u => u.Id.Contains(request.key));
            }
            if (!string.IsNullOrEmpty(request.sqlWhere))
            {
                objs = objs.Where(request.sqlWhere);
            }

            if (!string.IsNullOrEmpty(request.sort))
            {
                var sortfields = request.sort.Split(',');

                objs = objs.OrderBy($"{sortfields[0]} {sortfields[1]}");
            }else{
                objs = objs.OrderBy(u => u.Id);
            }
            result.Data = objs
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).ToList();
            result.Count = await objs.CountAsync();
            return result;
        }
        public void Add(AddOrUpdate{ClassName}Req request)
        {
            var obj = request.MapTo<{ClassName}>();
            var user = _auth.GetCurrentUser().User;
            //todo:补充或调整自己需要的字段
{InsertColumns}
            if(obj.KeyIsNull())  //如果主键为空，则生成默认值
            {
                obj.GenerateDefaultKeyVal();
            }

            SugarClient.Ado.BeginTran();
            SugarClient.Insertable(obj).ExecuteCommand();
            if (request.{SubClassName}Reqs != null && request.{SubClassName}Reqs.Any())
            {
                foreach (var detail in request.{SubClassName}Reqs)
                {
                    detail.{SubForeignKey} = obj.Id;
                    _{SubClassName}App.Add(detail);
                }
            }
            SugarClient.Ado.CommitTran();
        }
        public void Update(AddOrUpdate{ClassName}Req request)
        {
            var user = _auth.GetCurrentUser().User;
            SugarClient.Ado.BeginTran();
            if (request.{SubClassName}Reqs != null && request.{SubClassName}Reqs.Any())
            {
                //请求的id不在数据库的记录，需要删除
                var containids = request.{SubClassName}Reqs.Select(u => u.Id)
                    .Where(u => !string.IsNullOrEmpty(u)).ToList();
                if (containids.Any())
                {
                    SugarClient.Deleteable<{SubClassName}>(u => (!containids.Contains(u.Id)) && u.{SubForeignKey} == request.Id).ExecuteCommand();
                }
                //id为空的添加
                foreach (var detail in request.{SubClassName}Reqs.Where(u => string.IsNullOrEmpty(u.Id)))
                {
                    detail.{SubForeignKey} = request.Id;
                    _{SubClassName}App.Add(detail);
                }
                //更新id相同的
                foreach (var detail in request.{SubClassName}Reqs.Where(u => !string.IsNullOrEmpty(u.Id)))
                {
                    _{SubClassName}App.Update(detail);
                }
            }
            Repository.Update(u => new {ClassName}
            {
{UpdateColumns}
                //todo:补充或调整自己需要的字段
            }, u => u.Id == request.Id);
            SugarClient.Ado.CommitTran();
        }
        public {ModuleCode}(ISqlSugarClient client, IAuth auth,
        {SubModuleCode} {SubClassName}App) : base(client, auth)
        {
            _{SubClassName}App = {SubClassName}App;
        }
    }
}